/*
 * Copyright (c) 2011 learemraf@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.googlecode.frank.driver;

import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

/**
 * @author evansg
 */
public class Matchers {

	public static <T> Matcher<T> json(String toMatch) {
		return new JsonMatcher<T>(toMatch); 
	}

	public static <T> Matcher<T> containsJson(String key, String value) {
		return new ContainsJsonMatcher<T>(key, value);
	}

	public static <T> Matcher<T> contains(String value) {
		return new ContainsMatcher<T>(value);
	}

	/**
	 * @author evansg
	 * @param <T>
	 */
	protected static final class JsonMatcher<T> extends BaseMatcher<T> {

		private final String jsonToMatch;

		public JsonMatcher(String jsonToMatch) {
			this.jsonToMatch = jsonToMatch;
		}


		public boolean matches(Object item) {
			try {
				if (item instanceof Map<?, ?>) {
					Map<?, ?> itemAsMap = (Map<?, ?>)item;
					return deserialize(jsonToMatch, Map.class).equals(itemAsMap);
				}

				Map<?, ?> map1 = deserialize(jsonToMatch, Map.class);
				Map<?, ?> map2 = deserialize(item.toString(), Map.class);

				return map1.equals(map2);
			} catch (JsonParseException e) {
				throw new RuntimeException("Unable to parse json input", e);
			} catch (JsonMappingException e) {
				throw new RuntimeException("Unable to map json input", e);
			} catch (IOException e) {
				throw new RuntimeException("IOException", e);
			}
		}

		public void describeTo(Description description) {
			description.appendText("Json does not match, was").appendValue(jsonToMatch);
		}
	}

	/**
	 * @author evansg
	 * @param <T>
	 */
	protected static final class ContainsJsonMatcher<T> extends BaseMatcher<T> {

		private final String key;
		private final String value;

		public ContainsJsonMatcher(String key, String value) {
			this.key = key;
			this.value = value;
		}

		public boolean matches(Object item) {
			try {
				if (item instanceof Map<?, ?>) {
					return false;
				}

                if (null == value) {
					return false;
				}

				Map<?, ?> map = deserialize(item.toString(), Map.class);
				if (!map.containsKey(key)) {
					return false;
				}

				String value2 = (String)map.get(key);
				return value.equals(value2);
			} catch (JsonParseException e) {
				throw new RuntimeException("Unable to parse json input", e);
			} catch (JsonMappingException e) {
				throw new RuntimeException("Unable to map json input", e);
			} catch (IOException e) {
				throw new RuntimeException("IOException", e);
			}
		}

		public void describeTo(Description description) {
			description.appendText("Json does not contain key: ").appendValue(key)
					.appendText(" with value: ").appendValue(value);
		}
	}

	/**
	 * @author evansg
	 * @param <T>
	 */
	protected static final class ContainsMatcher<T> extends BaseMatcher<T> {
		private final String value;

		public ContainsMatcher(String value) {
			this.value = value;
		}

		public boolean matches(Object item) {
			if (null == item) {
				return false;
			}
			String itemAsToString = item.toString();
			return itemAsToString.contains(value);
		}

		public void describeTo(Description description) {
			description.appendText("String does not contain the text: ").appendValue(value);
		}
	}

	private static <T> T deserialize(String json, Class<T> clazz) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(json, clazz);
	}
}
